package com.itheima.controller;

import com.itheima.domain.Book;
import com.itheima.exception.BusinessException;
import com.itheima.service.BookService;
import com.itheima.utile.Code;
import com.itheima.utile.Result;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

// TODO 3.1 设置当前控制器为REST风格的控制器类，开发对应的CRUD功能，并调用对应的业务层接口
@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    BookService bookService;
    //json参数
    @PostMapping
    public Result save(@RequestBody Book book)
    {
        boolean flag = bookService.save(book);

        return new Result(flag? Code.SAVE_OK:Code.SAVE_ERR,flag);
    }
    //路径参数
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id){
        boolean delete = bookService.delete(id);
        return new Result(delete?Code.DELETE_OK:Code.DELETE_ERR,delete);

    }

    //json参数
    @PutMapping
    public Result update(@RequestBody Book book){
        boolean update = bookService.update(book);
        return new Result(update?Code.UPDATE_OK:Code.UPDATE_ERR,update);
    }

    //路径参数
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        Book book = bookService.getById(id);
        Integer code=book!=null?Code.GET_OK:Code.GET_ERR;
        String msg=book!=null?"":"数据查询失败，请重试";
        return new Result(code,book,msg);
    }

    @GetMapping
    public Result getAll(){
        List<Book> books = bookService.getAll();
        Integer code=books!=null?Code.GET_OK:Code.GET_ERR;
        String msg=books!=null?"":"数据查询失败，请重试";
        try {
            //模拟系统异常，将可能出现的异常进行包装，转换成自定义异常
            int i=1/0;
        }
        catch (Exception e) {
            throw new BusinessException(5001,"访问超时，请重试");
        }

        return new Result(code,books,msg);
    }

}














